var http = require("http");
var cheerio = require("cheerio");
var fs = require("fs");
var crypto = require("crypto");

var tiebaname = process.argv[2];
var pages      = process.argv[3] ? process.argv[3] : 1;
if(tiebaname != undefined){
  var path = __dirname + "/imgs/" + tiebaname + "/";
  if(!fs.existsSync(path)){
    fs.mkdirSync(path);
  }
  var url = "http://tieba.baidu.com/f?kw=" + tiebaname + "&tp=0&pn=";
  getImgsForTiebaPages(url, pages, path);
}else
  console.log('please add one tieba\'s name');

function getImgsForTiebaPages(url, pages, path){
  for(var i = 0; i < pages; i++){
    var pn = i * 50;
    getImgsForTieba(url + pn, path);
  }
}

function getImgsForTieba(url, path){
  console.log("url:"+url);
  http.get(url, function(res){
    res.setEncoding('utf8');
    var data='';
    res.on('data', function(chunk){
      data+=chunk;
    });
    res.on('end', function(){
      $ = cheerio.load(data);
      $('.vpic_wrap img').each(function(i, elem) {
        var url = $(this).attr('bpic');
        var name = md5(url) + i + ".jpg";
        saveImg(url, path + name);
      });	
    });
  }).on('error', function(e) {
    console.log('error'+e);
  });
}

function saveImg(url, name){
  http.get(url, function(res){
    res.setEncoding('binary');
    var data='';
    res.on('data', function(chunk){
      data+=chunk;
    });
    res.on('end', function(){
      fs.writeFile(name, data, 'binary', function (err) {
        if (err) throw err;
          console.log('file saved');
      });
    });
  }).on('error', function(e) {
    console.log('error'+e)
  });
}

function md5(data){
  hasher=crypto.createHash("md5");
  hasher.update(data);
  return hasher.digest('hex');
}